﻿using IdentityServer4.EntityFramework.Options;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace AuthenticationServer.Data
{
    //public class PersistedGrantDesignTimeDbContextFactory
    //{
    //}
    //public class PersistedGrantDesignTimeDbContextFactory : DesignTimeDbContextFactory<IdentityServerPersistedGrantDbContext>
    //{
    //}

    public class PersistedGrantDesignTimeDbContextFactory : IDesignTimeDbContextFactory<IdentityServerPersistedGrantDbContext>
    {
        public IdentityServerPersistedGrantDbContext CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

            var builder = new DbContextOptionsBuilder<IdentityServerPersistedGrantDbContext>();

            var connectionString = configuration.GetConnectionString("DefaultConnection");
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            builder.UseSqlServer(connectionString);

            return new IdentityServerPersistedGrantDbContext(builder.Options, 
                new OperationalStoreOptions() {
                    PersistedGrants = new TableConfiguration(IdentityServerTableNames.PersistedGrants),
                    ConfigureDbContext = b =>
                      b.UseSqlServer(connectionString,
                          sql => sql.MigrationsAssembly(migrationsAssembly))
                    //ConfigureDbContext = o => { o. }

                });
        }
    }
}
